# Name: JoinYearlyBufferGrid.py - MCBS 05/20/2015
# Description: Joins YearlyBuffer areas to grid and saves table

# import system module
import arcpy
from arcpy import env
#from arcpy.sa import *


# Set workspace environment:
#env.workspace = "CanasatData.gdb"
env.workspace = "C:\Users\Marcelo\Documents\Sugarcane\Offline Data\MunicBasedData\CanasatData.gdb"
env.overwriteOutput = True
#arcpy.CheckOutExtension("Spatial")

# Folder to store tables:
PathForTables = "C:\Users\Marcelo\Documents\Sugarcane\Offline Data\MunicBasedData\Tables"

# Input grid:
GridName   = "G1kmMiR"
# Buffer areas:
BaseBuffer = "BufCS5km_"
# Years to join to grid:
Years      = range(2004,2014)
# Output grids name:
BaseOut    = "G1kmMiRCSSugBuf5km"

# Merge buffer files: 
# OBS: Buffer features must all have a column called SugBuffer with the buffer year as input
# First create list of files to merge:
ListBuffers = [BaseBuffer + str(Years[0])]
for y in Years[1:len(Years)]:
	ListBuffers.append( BaseBuffer + str(y) )
# Merge buffers:	
arcpy.Merge_management(ListBuffers, "MergedBuffers")
arcpy.SpatialJoin_analysis(GridName, "MergedBuffers", BaseOut,
						   "JOIN_ONE_TO_MANY", "KEEP_ALL", "",
						   "COMPLETELY_WITHIN", "", "")
	
# Save .dbf tables in specified folder
TableName    = BaseOut + ".dbf"
arcpy.TableToTable_conversion(BaseOut, PathForTables, TableName)

# # Export table as .csv:
# import win32com.client

# # Define excel
# excel = win32com.client.Dispatch('Excel.Application')

# # Folder to store tables:

# TableName = OutName
# TableNameDbf = TableName + ".dbf"
# TableNameCsv = TableName + ".csv"

# InputDBF         = PathForTablesExcel + TableNameDbf
# OutputCSV        = PathForTablesExcel + TableNameCsv

# # Convert .dbf tables into .csv using excel.
# workbook     = excel.Workbooks.Open(InputDBF)
# workbook.SaveAs(OutputCSV,FileFormat=24)
# print "Output table saved: " + TableNameCsv
# print " "

# excel.Quit()
